<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Api\BaseController;
use App\Models\User;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UserController extends BaseController
{
    //

    public function login(Request $request){
        try{
            $code = $request->input('code', '');
            if (empty($code)) return $this->response(400, 'code参数错误');
            $config = config('wechat.mini_program');
//        获取easywechat 小程序的对象
            $app = Factory::miniProgram($config);
            $result = $app->auth->session($code);

            $user = User::where('openid', $result['openid'])->first();
            if (empty($user)) {
                $data = [
                    'openid' => $result['openid']
                ];
                if (!User::create($data)) return $this->response(400, '用户写入失败');
            }
            return $this->response(200, '登录成功', $result);
        }catch (\Throwable $e) {
            return $this->response(500, $e->getMessage());
        }

    }

    public function sendMessage(Request $request) {
        $data = [
            'template_id' => '9TekBb58fwHxA1iXMNg8WgvVAm1e4gOnmYrqcHMGClk', // 所需下发的订阅模板id
            'touser' => 'o807d4oPJr1vqYkkVgF4qlzVKl7s',     // 接收者（用户）的 openid
            'page' => 'page/index/index',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                'thing1' => [
                    'value' => '完成计算机网络课程的复习',
                ],
                'time4' => [
                    'value' => '2021-03-11',
                ],
                'character_string2' => [
                    'value' => '2021-03-15'
                ]
            ],
        ];

        $config = config('wechat.mini_program');
//        获取easywechat 小程序的对象
        $app = Factory::miniProgram($config);

        return $app->subscribe_message->send($data);
    }

    public function upload(Request $request) {
        $path = $request->file('avatar')->store('public/avatars');

        $url = Storage::url($path);

        return config('app.url') . $url;
    }
}











